var evapp = new Framework7({
    root : "#evapp",
    name : "优势累积",
    version : "1.0.0",
    view : {
        pushState:true
    },
    dialog:{
        buttonOk:"确认",
        buttonCancel:"取消"
    },
    routes : [
        {
            path : "/home/",
            url  : "./pages/home.html"
        },
        {
            path : "/test/:testno/",
            templateUrl  : "./pages/test.html"
        },
        {
            path : "/results/",
            url  : "./pages/results.html"
        }
    ]

});
var evMainView = evapp.views.create('.view-main',{});
// initwxsdk();
/*全局变量*/
var $$ = Dom7;
var Globaluid;
var Globaltestno,Globalcurrentq,Globalqnum,Globalans;

var qitemTemplate = $$('script#Qitem').html();
var compiledQitemTemplate = Template7.compile(qitemTemplate);
var testItemTemplate = $$('script#Testitem').html();
var compiledTestItemTemplate = Template7.compile(testItemTemplate);
var resultItemTemplate = $$('script#Resultitem').html();
var compiledResultItemTemplate = Template7.compile(resultItemTemplate);
/*页面事件*/
$$(document).on('page:init','.page[data-name="Home"]',function () {
    //console.log('page home init');
    getfinishstatus();
});
$$(document).on('page:init','.page[data-name="Test"]',function () {
    //console.log('page test init');
    Globaltestno = $$('.page[data-name="Test"]').data('test');
    Globalcurrentq = 0;
    Globalqnum = Globaldata[Globaltestno]['qnum'];
    Globalans = {};

    loadnextq();
});
$$(document).on('page:init','.page[data-name="Results"]',function () {
    //console.log('page results init');
    getresults();
});
$$(document).on('click','.nextq-btn',function () {
    if (Globalcurrentq < Globalqnum-1) {
        //保存答案
        var data = evapp.form.convertToData('#ansform');
        if (data.qans===undefined) {evapp.dialog.alert('请选择您的答案','');return;}
        //console.log(data);
        Globalans[Globalcurrentq] = {ans:data.qans,type:data.qtype};
        Globalcurrentq++;
        //载入下一题
        if (Globalcurrentq < Globalqnum) {
            loadnextq();
            //设定progress
            evapp.progressbar.set('.progressbar', Globaldata[Globaltestno]['qdata'][Globalcurrentq]['progress']);
            if (Globalcurrentq === Globalqnum - 1) {
                $$('.page[data-name="Test"] .nextq-btn span').html('提交问卷');
            }
        }
    }else {
        var data = evapp.form.convertToData('#ansform');
        if (data.qans===undefined) {evapp.dialog.alert('请选择您的答案','');return;}
        //console.log(data);
        Globalans[Globalcurrentq] = {ans:data.qans,type:data.qtype};
        submit();
    }
});
$$(document).on('click','.show-results-btn',function () {
    evMainView.router.navigate('/results/');
});
/*工具函数*/
function checklogin() {
    //console.log('checklogin');
    evapp.request({
        async:false,
        method:'GET',
        url:"http://api.nldou.com/evaluation/checklogin",
        data:{},
        dataType:'json',
        xhrFields:{"withCredentials":true},
        success:function (res) {
            //console.log(res);
            if (res.code==1){
                if (res.data.status == 1) {
                    loginscreen();
                }else{
                    Globaluid = res.data.uid;
                    kp.stop();
                    evMainView.router.navigate('/home/',{reloadCurrent:true});
                }
            }else{
                //session不存在
                window.location.href='http://api.nldou.com/ucenter/weixinlogin?pid=2539';
            }
        }
    })
}
function loginscreen() {
    //console.log('loginscreen');
    evapp.dialog.prompt(
        "请输入您的姓名","",function(name){
            name = name.replace(/(^\s*)|(\s*$)/g, "");
            if (!name) {
                evapp.dialog.alert("输入的姓名不能为空","",loginscreen);
                return;
            }
            evapp.request({
                async:false,
                method:'POST',
                url:"http://api.nldou.com/evaluation/firstlogin",
                data:{name:name},
                dataType:'json',
                xhrFields:{"withCredentials":true},
                success:function(res){
                    //console.log(res);
                    if (res.code==1){
                        Globaluid = res.data.uid;
                        kp.stop();
                        evMainView.router.navigate('/home/',{reloadCurrent:true});
                    }else{
                        //session不存在
                        window.location.href='http://api.nldou.com/ucenter/weixinlogin?pid=2539';
                    }
                }
            })
        }
    )
}
function initwxsdk(){
    evapp.request({
        url:"http://api.nldou.com/weixinapi/init_wx_jsapi",
        method:"GET",
        data: {fromUrl:window.location.href},
        dataType:'json',
        success: function (res) {
            if(res.code==1){
                wx.config({
                    debug: false,
                    appId: res.data.appid,
                    timestamp: res.data.timestamp,
                    nonceStr: res.data.nonceStr,
                    signature: res.data.signature,
                    jsApiList: ['onMenuShareTimeline','onMenuShareAppMessage','hideMenuItems','chooseImage'
                        ,'uploadImage','getLocalImgData']
                });
            }
        }
    });
    wx.ready(function () {
        wx.hideMenuItems({
            menuList: ['menuItem:share:qq', 'menuItem:share:weiboApp', 'menuItem:share:facebook', 'menuItem:share:QZone'
                ,'menuItem:copyUrl', 'menuItem:openWithQQBrowser', 'menuItem:openWithSafari']
        });
        wx.onMenuShareTimeline({
            title: '优势累积课程测试',
            link: 'http://api.nldou.com/ucenter/weixinlogin?pid=2539',
            imgUrl: 'http://wap.nldou.com/evaluation/img/adv-logo.jpg'
        });
        wx.onMenuShareAppMessage({
            title: '优势累积课程测试',
            desc: '为保证课程效果，请认真填写',
            link: 'http://api.nldou.com/ucenter/weixinlogin?pid=2539',
            imgUrl: 'http://wap.nldou.com/evaluation/img/adv-logo.jpg',
            type: 'link'
        });
    });
}
function loadnextq() {
    var qsort = Globalcurrentq+1;
    $$('.page[data-name="Test"] .qsort').html(qsort);
    var remainq = Globalqnum-(Globalcurrentq+1);
    $$('.page[data-name="Test"] .qremain').html(remainq);
    var html = compiledQitemTemplate(Globaldata[Globaltestno]['qdata'][Globalcurrentq]);
    $$('.page[data-name="Test"] .answer-container').html(html);
}
function submit() {
    evapp.dialog.preloader('提交中');
    evapp.request.post("http://api.nldou.com/evaluation/submit",{uid:Globaluid,data:Globalans,testno:Globaltestno},function (res) {
        //console.log(res);
        if (res.code==1){
            evapp.dialog.close();
            evapp.dialog.alert('提交成功','',function () {
                evMainView.router.navigate('/home/',{reloadCurrent:true});
            });
        }else{
            evapp.dialog.close();evapp.dialog.alert('提交失败请重试','');
        }
    },function () {evapp.dialog.close();evapp.dialog.alert('提交失败请重试','');},'json');
}
function getfinishstatus() {
    evapp.request.get("http://api.nldou.com/evaluation/getFinishStatus",{uid:Globaluid},function (res) {
        if (res.code==1){
            $$('.page[data-name="Home"] .complishednum').html(res.data.num);
            var html = compiledTestItemTemplate(res.data.complished);
            $$('.page[data-name="Home"] .test-list ul').html(html);
        }
    },function () {},'json');
}
function getresults() {
    evapp.request.get("http://api.nldou.com/evaluation/getResults",{uid:Globaluid},function (res) {
        if (res.code==1){
            //console.log(res.data);
            var html = compiledResultItemTemplate(res.data);
            $$('.page[data-name="Results"] .page-content').html(html);
        }
    },function () {},'json');
}
/*开屏*/
function Loginanim(speed){
    this.delta=0;
    this.speed=speed;
    this.animid=0;
}
Loginanim.prototype={
    constructor:Loginanim,
    anim:function () {
        this.delta+=this.speed;
        var d0 = Math.abs(Math.sin(Math.PI/2+this.delta));
        var d1 = Math.abs(Math.sin(Math.PI/3+this.delta));
        var d2 = Math.abs(Math.sin(Math.PI/6+this.delta));
        $$('.login-anim-btn').eq(0).css({'opacity':d0});
        $$('.login-anim-btn').eq(1).css({'opacity':d1});
        $$('.login-anim-btn').eq(2).css({'opacity':d2});
        this.animid=requestAnimationFrame(this.anim.bind(this));
    },
    start:function () {
        this.animid = requestAnimationFrame(this.anim.bind(this));
    },
    stop:function () {
        cancelAnimationFrame(this.animid);
    }
};
var kp = new Loginanim(0.03);
kp.start();
initwxsdk();
checklogin();